import 'dart:convert';

import 'package:base_lib/index.dart';
import 'package:doctor_inquiry_lib/constant/constant.dart';

import 'MessageNormal.dart';
import 'package:doctor_login_lib/login/entity/doctor_login_entity.dart'
    as DoctorBean;
import 'package:doctor_inquiry_lib/chat_list/entity/doctor_patient_entity.dart'
    as DoctorPatientBean;

class MsgListEntity {}

class MsgEntity {
  ///自定义消息ID，flutter端生成，用于更新flutter UI中消息状态（成功，进度，失败）
  String customMsgID;

  String msgID;

  num timestamp;

  /// 消息的发送方ID
  /// 获取消息发送者 userID
  String senderID;

  /// 获取消息发送者昵称
  String nickName;

  /// 用户ID
  /// 如果是单聊消息，userID 为会话用户 ID，否则为 null。
  /// 假设自己和 userA 聊天，无论是自己发给 userA 的消息还是 userA 发给自己的消息，这里的 userID 均为 userA
  String userID;

  /// 消息发送者是否是自己
  bool isSelf;

  /// 消息自己是否已读
  bool isRead;

  /// 消息对方是否已读（只有 C2C 消息有效）
  bool isPeerRead;

  /// 消息状态
  int status;

  /// 消息类型
  String elemType;

  /// 消息类型的中文显示，如果是文字消息，直接展示
  String desc;

  /// 消息类型 为 V2TIM_ELEM_TYPE_CUSTOM，customElem 会存储自定义消息内容
  String customElem;

  /// 消息类型 为 V2TIM_ELEM_TYPE_TEXT，textElem 会存储文本消息内容
  String textElem;

  /// 消息类型 为 V2TIM_ELEM_TYPE_IMAGE，imageElem 会存储图片消息内容
  // ImgMsgContentEntity imageElem;
  String imgPath;

  String thumbPath;

  /// 消息类型 为 V2TIM_ELEM_TYPE_SOUND，soundElem 会存储语音消息内容
  // SoundMsgContentEntity soundElem;

  String soundPath;

  int soundDuration;

  static WMessageState getWMessageStatus(int statusInt) {
    /**
        //      * 消息状态
        //      * public static final int V2TIM_MSG_STATUS_SENDING = 1;
        //      * public static final int V2TIM_MSG_STATUS_SEND_SUCC = 2;
        //      * public static final int V2TIM_MSG_STATUS_SEND_FAIL = 3;
        //      * public static final int V2TIM_MSG_STATUS_HAS_DELETED = 4;
        //      * public static final int V2TIM_MSG_STATUS_LOCAL_REVOKED = 6;
        //      */
    WMessageState state;
    switch (statusInt) {
      case 1:
        state = WMessageState.sending;
        break;
      case 2:
        state = WMessageState.send_succeed;
        break;
      case 3:
        state = WMessageState.send_failed;
        break;
      default:
        state = WMessageState.send_succeed;
        break;
    }

    return state;
  }

  ///消息bean转化成UIBean
  static WMessage MsgBean2WMessage(
      MsgEntity msgBean,
      DoctorPatientBean.PatientDatum patientDatum,
      DoctorBean.DoctorUser doctorUser) {
    WMessage wMessage;

    /// 原生端，如下定义
    ///  public static enum MsgType {
    //         text,
    //         sound,
    //         image,
    //         face,
    //         custom, //包含 card  hint
    //         error,//不支持的消息
    //     }
    // FLog(msgBean.toJson());
    // FLog('消息转换开始  ${msgBean.msgID}   ${msgBean.elemType}');
    WUserInfo fromUser = new WUserInfo();
    WUserInfo targetUser = new WUserInfo();
    if (msgBean.isSelf) {
      fromUser
        ..id = msgBean.senderID
        ..username = doctorUser?.phone ?? ''
        ..nick = doctorUser?.doctorName ?? ''
        ..headUrl = doctorUser?.faceImage ?? '';

      targetUser
        ..id = msgBean.userID
        ..username = patientDatum?.phone ?? ''
        ..nick = patientDatum?.personName ?? ''
        ..headUrl = patientDatum?.faceImage ?? '';
    } else {
      targetUser
        ..id = doctorUser?.keyID ?? ''
        ..username = doctorUser?.phone ?? ''
        ..nick = doctorUser?.doctorName ?? ''
        ..headUrl = doctorUser?.faceImage ?? '';

      fromUser
        ..id = msgBean.senderID
        ..username = patientDatum?.phone ?? ''
        ..nick = patientDatum?.personName ?? ''
        ..headUrl = patientDatum?.faceImage ?? '';
    }

    switch (msgBean.elemType) {
      case "text":
        wMessage = WTextMessage()..text = msgBean.textElem;
        break;

      case "sound":
        wMessage = WVoiceMessage(
            path: msgBean.soundPath, duration: msgBean.soundDuration);
        break;

      case "image":
        wMessage = WImageMessage()
              ..thumbPath = msgBean.thumbPath
              ..path = msgBean.imgPath
            // ..urls = msgBean.imageElem.imgList.map((e) => e.url).toList()
            ;
        break;

      case "custom":
        // FLog(msgBean.customElem);
        //{"customType":"sys","data":{"startInquiry":true,"inquiryID":"20103017210429896872212211"}}
        //{"customType":"sys","childType":"end-inquiry","data":{}}
        //{"customType":"hint","childType":"both","data":{"text":"问诊结束"}}
        //{"customType":"hint","childType":"both","data":{"text":"视频问诊"}}
        //{"customType":"card","childType":"patientInfo","data":{"title":"您要为谁咨询","doctorID":"20031111131047917440531001","inquiryID":"20103017203114960552212211"}}
        //
        var jsonCustomEle = jsonDecode(msgBean.customElem);
        var jsonCustomEleData = jsonCustomEle['data'];
        switch (jsonCustomEle['customType']) {
          case 'hint':
            wMessage = WHintMessage()..hint = jsonCustomEleData['text'];
            break;
          case 'sys':
            wMessage = WSysMessage()
              ..body = msgBean.customElem
              ..data = jsonEncode(jsonCustomEleData)
              ..childType = jsonCustomEle['childType'] ?? '';
            break;
          case 'card':
            wMessage = WCardMessage()
              ..childType = jsonCustomEle['childType']
              ..title = jsonCustomEleData['title'] ?? ''
              ..doctorID = jsonCustomEleData['doctorID'] ?? ''
              ..inquiryID = jsonCustomEleData['inquiryID'] ?? '';
            break;

          default:
            wMessage = WHintMessage()..hint = '暂不支持的消息';
            break;
        }

        break;

      default:
        wMessage = new WMessage();
        break;
    }
    // FLog('消息转换结束  ${msgBean.msgID}   ${msgBean.elemType}');
    wMessage
      ..customMsgID = msgBean.customMsgID ?? ''
      ..isSend = msgBean.isSelf
      ..isPeerRead = msgBean.isPeerRead
      ..state = getWMessageStatus(msgBean.status)
      ..msgID = msgBean.msgID
      ..createTime = msgBean.timestamp
      ..from = fromUser
      ..target = targetUser;
    return wMessage;
  }

  MsgEntity({
    this.customMsgID,
    this.msgID,
    this.timestamp,
    this.senderID,
    this.nickName,
    this.userID,
    this.isSelf,
    this.isRead,
    this.isPeerRead,
    this.status,
    this.elemType,
    this.desc,
    this.customElem,
    this.textElem,
    // this.imageElem,
    // this.soundElem,
    this.soundPath,
    this.soundDuration,
    this.imgPath,
    this.thumbPath,
  });

  MsgEntity.fromJson(dynamic json) {
    customMsgID = json["customMsgID"];
    msgID = json["msgID"];
    senderID = json["senderID"];
    nickName = json["nickName"];
    userID = json["userID"];
    isSelf = json["isSelf"];
    isRead = json["isRead"];
    isPeerRead = json["isPeerRead"];
    status = json["status"];
    elemType = json["elemType"];
    desc = json["desc"];
    timestamp = json['timestamp'];
    customElem = json["customElem"] ?? '';
    textElem = json["textElem"] ?? '';
    imgPath = json['imgPath'] ?? '';
    thumbPath = json['thumbPath'] ?? '';
    soundPath = json['soundPath'] ?? '';
    soundDuration = json['soundDuration'] ?? '';
    // imageElem = json["imageElem"];
    // soundElem = json["soundElem"]??'';
  }

  Map<String, dynamic> toJson() {
    var map = <String, dynamic>{};
    map["customMsgID"] = customMsgID;
    map["msgID"] = msgID;
    map["senderID"] = senderID;
    map["userID"] = userID;
    map["isSelf"] = isSelf;
    map["isRead"] = isRead;
    map["isPeerRead"] = isPeerRead;
    map["senderID"] = senderID;
    map["status"] = status;
    map["elemType"] = elemType;
    map["desc"] = desc;
    map['timestamp'] = timestamp;
    map["customElem"] = customElem;
    map["textElem"] = textElem;
    map['imgPath'] = imgPath;
    map['thumbPath'] = thumbPath;
    map['soundPath'] = soundPath;
    map['soundDuration'] = soundDuration;
    // map["imageElem"] = imageElem;
    // map["soundElem"] = soundElem;
    return map;
  }
}

// class ImgMsgContentEntity {
//   /// 原图本地文件路径，只对消息发送方有效
//   String path;
//
//   /// 包含的图片列表
//   List<ImgContentItemEntity> imgList;
//
//   ImgMsgContentEntity({this.path, this.imgList});
//
//   ImgMsgContentEntity.fromJson(dynamic json) {
//     path = json["path"];
//     imgList = json["imgList"] == null
//         ? null
//         : (json["imgList"] as List)
//             .map((e) => ImgContentItemEntity.fromJson(e));
//   }
//
//   Map<String, dynamic> toJson() {
//     var map = <String, dynamic>{};
//     map["path"] = path;
//     map["imgList"] = imgList;
//     return map;
//   }
// }
//
// class ImgContentItemEntity {
//   /// 消息内部 ID
//   String uuid;
//
//   /// 数据大小
//   int size;
//
//   /// 的 URL 下载地址
//   String url;
//
//   ImgContentItemEntity({this.uuid, this.size, this.url});
//
//   ImgContentItemEntity.fromJson(dynamic json) {
//     uuid = json["uuid"];
//     size = json["size"];
//     url = json["url"];
//   }
//
//   Map<String, dynamic> toJson() {
//     var map = <String, dynamic>{};
//     map["uuid"] = uuid;
//     map["size"] = size;
//     map["url"] = url;
//     return map;
//   }
// }
//
// class SoundMsgContentEntity {
//   /// 需要发送的语音文件的路径（只有发送方才能获取到）
//   String path = "";
//
//   /// 语音消息内部 ID
//   String uuid;
//
//   /// 语音数据大小
//   int dataSize;
//
//   /// 语音的 URL 下载地址
//   String url;
//
//   SoundMsgContentEntity({this.path, this.uuid, this.dataSize, this.url});
//
//   SoundMsgContentEntity.fromJson(dynamic json) {
//     path = json["path"] ?? '';
//     uuid = json["uuid"];
//     dataSize = json["dataSize"];
//     url = json["url"];
//   }
//
//   Map<String, dynamic> toJson() {
//     var map = <String, dynamic>{};
//     map["path"] = path;
//     map["uuid"] = uuid;
//     map["dataSize"] = dataSize;
//     map["url"] = url;
//     return map;
//   }
// }
